import sqlite3
from flask import Flask, render_template, request, redirect, url_for, session, jsonify, flash
from datetime import datetime, timedelta

app = Flask(__name__)
app.secret_key = 'your_secret_key'


# 数据库连接函数
def get_db_connection():
    conn = sqlite3.connect('users.db')
    conn.row_factory = sqlite3.Row  # 使得查询结果可以通过列名访问
    return conn


# 创建数据库表
def create_table():
    conn = get_db_connection()
    conn.execute('''
        CREATE TABLE IF NOT EXISTS users (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            username TEXT NOT NULL,
            machine_id TEXT NOT NULL,
            password TEXT NOT NULL,
            user_type TEXT NOT NULL
        )
    ''')
    conn.commit()
    conn.close()


create_table()


# 登录
@app.route('/', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        user_type = request.form['user_type']
        username = request.form['username']
        password = request.form['password']

        conn = get_db_connection()
        user = conn.execute('SELECT * FROM users WHERE username = ? AND user_type = ? AND password = ?',
                            (username, user_type, password)).fetchone()
        conn.close()

        if user:
            session['username'] = username
            session['user_type'] = user_type
            if user_type == 'student':
                return redirect(url_for('student_dashboard', username=username))
            elif user_type == 'teacher':
                return redirect(url_for('teacher_dashboard', username=username))
            elif user_type == 'parent':
                return redirect(url_for('parent_dashboard', username=username))

        flash('登录失败，用户名或密码错误！', 'danger')
        return redirect(url_for('login'))

    return render_template('login.html')


# 注册
@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        user_type = request.form['user_type']
        username = request.form['username']
        machine_id = request.form['machine_id']
        password = request.form['password']

        conn = get_db_connection()
        existing_user = conn.execute('SELECT * FROM users WHERE username = ?', (username,)).fetchone()

        if existing_user:
            flash('用户名已存在，请选择其他用户名。', 'danger')
            conn.close()
            return redirect(url_for('register'))

        conn.execute('INSERT INTO users (username, machine_id, password, user_type) VALUES (?, ?, ?, ?)',
                     (username, machine_id, password, user_type))
        conn.commit()
        conn.close()

        flash('注册成功！', 'success')
        return redirect(url_for('register_success'))

    return render_template('register.html')


@app.route('/register_success')
def register_success():
    return render_template('register_success.html')


# 忘记密码
@app.route('/forgot_password', methods=['GET', 'POST'])
def forgot_password():
    if request.method == 'POST':
        user_type = request.form['user_type']
        username = request.form['username']
        new_password = request.form['new_password']

        conn = get_db_connection()
        user = conn.execute('SELECT * FROM users WHERE username = ? AND user_type = ?',
                            (username, user_type)).fetchone()

        if user:
            conn.execute('UPDATE users SET password = ? WHERE username = ? AND user_type = ?',
                         (new_password, username, user_type))
            conn.commit()
            conn.close()
            flash('密码重置成功！', 'success')
            return redirect(url_for('password_reset_success'))
        else:
            flash('用户名不存在。', 'danger')
            conn.close()
            return redirect(url_for('forgot_password'))

    return render_template('forgot_password.html')


@app.route('/password_reset_success')
def password_reset_success():
    return render_template('password_reset_success.html')


# 学生页面
@app.route('/student_dashboard/<username>', methods=['GET', 'POST'])
def student_dashboard(username):
    if 'user_type' not in session or session['user_type'] != 'student':
        return redirect(url_for('login'))

    # 此处可添加更多学生功能
    return render_template('student_dashboard.html', username=username)


# 学生选择加入考试页面
@app.route('/student_class/<username>/<class_name>', methods=['GET', 'POST'])
def student_class(username, class_name):
    if 'user_type' not in session or session['user_type'] != 'student':
        return redirect(url_for('login'))

    # 此处可添加更多学生选择考试的功能
    return render_template('student_class.html', username=username, class_name=class_name)


# 考试页面
@app.route('/exam/<class_name>/<exam_name>', methods=['GET', 'POST'])
def exam_page(class_name, exam_name):
    if 'user_type' not in session or session['user_type'] != 'student':
        return redirect(url_for('login'))

    # 此处可添加考试页面的功能，例如显示考试题目等
    return render_template('exam.html', class_name=class_name, exam_name=exam_name)


# 新增的考试完成页面
@app.route('/exam_finished/<class_name>/<exam_name>', methods=['GET'])
def exam_finished(class_name, exam_name):
    if 'user_type' not in session or session['user_type'] != 'student':
        return redirect(url_for('login'))

    # 显示考试完成后的结果或总结
    return render_template('exam_finished.html', class_name=class_name, exam_name=exam_name,
                           username=session['username'])


# 提交考试
@app.route('/submit_exam/<class_name>/<exam_name>', methods=['POST'])
def submit_exam(class_name, exam_name):
    if 'user_type' not in session or session['user_type'] != 'student':
        return redirect(url_for('login'))

    # 处理考试提交逻辑
    return redirect(url_for('exam_finished', class_name=class_name, exam_name=exam_name))


# 老师页面
@app.route('/teacher_dashboard/<username>', methods=['GET', 'POST'])
def teacher_dashboard(username):
    if 'user_type' not in session or session['user_type'] != 'teacher':
        return redirect(url_for('login'))

    # 此处可添加更多教师功能
    return render_template('teacher_dashboard.html', username=username)


@app.route('/manage_class/<username>', methods=['GET', 'POST'])
def manage_class(username):
    if 'user_type' not in session or session['user_type'] != 'teacher':
        return redirect(url_for('login'))

    # 此处可添加班级管理功能
    return render_template('teacher_dashboard.html', username=username)


@app.route('/class_management/<class_name>', methods=['GET'])
def class_management(class_name):
    if 'user_type' not in session or session['user_type'] != 'teacher':
        return redirect(url_for('login'))

    # 此处可添加班级管理功能
    return render_template('class_management.html', class_name=class_name)


# 设置考试时间页面
@app.route('/set_exam_time/<username>', methods=['GET', 'POST'])
def set_exam_time(username):
    if 'user_type' not in session or session['user_type'] != 'teacher':
        return redirect(url_for('login'))

    # 此处可添加设置考试时间功能
    return render_template('set_exam_time.html', username=username)


# 家长页面
@app.route('/parent_dashboard/<username>')
def parent_dashboard(username):
    if 'user_type' not in session or session['user_type'] != 'parent':
        return redirect(url_for('login'))

    # 此处可添加更多家长功能
    return render_template('parent_dashboard.html', username=username)


# 记录作弊行为
@app.route('/record_cheating', methods=['POST'])
def record_cheating():
    if 'username' in session:
        username = session['username']
        # 处理作弊记录逻辑
        return jsonify({'terminate': False})
    return jsonify({'error': 'User not logged in'}), 401


# 终止考试
@app.route('/terminate_exam')
def terminate_exam():
    session.pop('exam', None)
    flash("由于检测到多次作弊行为，您的考试已被终止。", 'danger')
    return redirect(url_for('login'))


if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5000, debug=True)
